package com.cwvs.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * 
 * 地区相关DAO
 */
@Repository
public class AppAreaDao {
	@Resource
	private JdbcTemplate jdbcTemplate;

	/**
	 * 地区新增
	 * 
	 * @param m
	 * @return
	 */
	public boolean add(Map<String, Object> m) {
		return false;

	}

	/**
	 * 通过父级获取地区列表
	 */
	public List<Map<String, Object>> areaList(String parentId) {
		if (StringUtils.isBlank(parentId)) {
			parentId = "0";
		}
		StringBuffer sbf = new StringBuffer();
		sbf.append("SELECT ID,CODE,NAME,LEVEL FROM APP_AREA WHERE STATUS=0 AND PARENT_ID=? ");
		return jdbcTemplate.queryForList(sbf.toString(),
				new Object[] { parentId });
	}

	/**
	 * 通过ID获取区域
	 */
	public Map<String, Object> getParentArea(String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ID", "0");
		map.put("NAME", "中国");
		map.put("LEVEL", "0");
		if (StringUtils.isBlank(id)) {
			return map;
		}
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT ID,CODE,NAME,LEVEL FROM APP_AREA WHERE STATUS=0 AND  ID=?   ");
		List<Map<String, Object>> ls = jdbcTemplate.queryForList(
				sbf.toString(), new Object[] { id });
		if (!ls.isEmpty()) {
			return ls.get(0);
		}
		return map;
	}
	/**
	 * 新增或修改
	 * @param m
	 * @return
	 */
	public boolean saveOrUpdate(Map<String, Object> m) {
		if (StringUtils.isBlank(MapUtils.getString(m, "ID"))) {
			String id = UUID.randomUUID().toString();
			StringBuffer sbf = new StringBuffer();
			sbf.append("INSERT INTO APP_AREA(ID,CODE,NAME,LEVEL,STATUS,CTIME,UTIME,PARENT_ID)");
			sbf.append("VALUES(?,?,?,?,?,?,?,?)");
			List<Object> params = new ArrayList<Object>();
			params.add(id);
			params.add(MapUtils.getString(m, "CODE"));
			params.add(MapUtils.getString(m, "NAME"));
			params.add(MapUtils.getString(m, "LEVEL"));
			params.add(0);
			params.add(new Date());
			params.add(new Date());
			params.add(MapUtils.getString(m, "PARENT_ID"));
			return jdbcTemplate.update(sbf.toString(), params.toArray()) > 0;
		} else {
			StringBuffer sbf = new StringBuffer();
			sbf.append(" UPDATE APP_AREA SET CODE=?, NAME=? ");
			sbf.append(" ,UTIME=? WHERE ID=? ");
			return jdbcTemplate.update(
					sbf.toString(),
					new Object[] { MapUtils.getString(m, "CODE"),
							MapUtils.getString(m, "NAME"), new Date(),
							MapUtils.getString(m, "ID") }) > 0;
		}
	}
}
